package com.littleHan.brushQuestions.shiro;

import com.littleHan.brushQuestions.web.start.pojo.GeneralUser;
import com.littleHan.brushQuestions.web.start.service.LoginService;
import com.littleHan.brushQuestions.token.JwtToken;
import com.littleHan.brushQuestions.utils.StringUtil;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 自定义密码管理器
 */
@Component
public class MyCredentialsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        JwtToken jwtToken=(JwtToken) token;
        if(jwtToken.getPassword()==null){
            return true;
        }
        String inPassword=new String(jwtToken.getPassword());
        String username=String.valueOf(info.getPrincipals());
        String dbPassword=(String)info.getCredentials();
        GeneralUser generalUser=loginService.getGeneralUserByUsername(username);
        //获取盐
        String salt=generalUser.getSalt();
        return this.equals(StringUtil.md5(inPassword+salt),dbPassword);
    }
}
